<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>post请求</title>
</head>
<body>
    <h1>POST请求</h1>
    <form id="form">
      <input type="text" name="name">
      <input type="text" name="age">
      <input type="text" name="sex">
      <button id="btn">提交</button>
    </form>
    <script>
        const oForm = document.getElementById('form')
        const oName = document.querySelector('#form input[name=name]');
        const oAge = document.querySelector('#form input[name=age]');
        const oSex = document.querySelector('#form input[name=sex]');
        const oBtn = document.getElementById('btn')

        oForm.onsubmit = function(){
            //收集表单数据
            const nameValue = oName.value;
            const ageValue = oAge.value;
            const sexValue = oSex.value; 

            //发送ajax数据请求创建数据
            const xhr = new XMLHttpRequest()

            xhr.open("POST","/addUser","true")
            
            //设置请求头 contentType的类型要跟send数据类型保持一致,
            //否则报错SyntaxError: Unexpected token n in JSON at position 0
            // xhr.setRequestHeader("Content-Type", "application/json;charset=utf-8")
            
            xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8")
            // post通过请求体新增数据 
            // xhr.send("name='张三'&age='18'&sex='男'")
            xhr.send(`name=${nameValue}&age=${ageValue}&sex=${sexValue}`);
            // xhr.send(`name=${nameValue}&age=${ageValue}&sex=${sexValue}`)
            // xhr.send(JSON.stringify({
            //     name: nameValue,
            //     age: ageValue,
            //     sex: sexValue
            // }))

            xhr.onreadystatechange = function(){
                // 判断前后端的数据传输是否完成
                if(xhr.readyState === 4&&(xhr.status>=200 && xhr.status<=299)){
                    // 获取响应数据 一般响应数据都是JSON串,需手动转成对象
                    // console.log(JSON.parse(xhr.responseText));
                    console.log(xhr.responseText);
                    
                    
                }
            }
            return false
        }



    </script>
</body>
</html>